import { ElMessage } from "element-plus";
let baseUrl = '';
const fetch = (url: string, options?: any): Promise<any> => {
	const token = useCookie("token");
	const headers = { // headers信息
		// 'Authorization' : `Bearer ${token.value}`
	}
	const runtimeConfig = useRuntimeConfig()
	// console.log("runtimeConfig：apiBase=>")
	// console.log(runtimeConfig.public.apiBase)
	baseUrl = runtimeConfig.public.apiBase
	const reqUrl = baseUrl + url
	return new Promise((resolve, reject) => {
		useFetch(reqUrl, { ...options, headers }).then(({ data }: any) => {
			const value = data.value
			// console.log(data)
			if (!data._rawValue) {
				// 这里处理错误回调
				reject(value)
			} else if (data._rawValue.code === 200) { // 请求接口成功
				// console.log(`接口${reqUrl}返回值：`)
				// console.log(data._rawValue)
				resolve(data._rawValue)
			} else { // 请求接口失败
				ElMessage({
					message: data._rawValue.message,
					type: 'error',
				})
			}
		}).catch((err: any) => {
			reject(err)
		})
	})
}

export default new class Http {

	get(url: string, params?: any): Promise<any> {
		return fetch(url, { method: 'get', params })
	}

	post(url: string, params?: any): Promise<any> {
		return fetch(url, { method: 'post', params })
	}

	put(url: string, body?: any): Promise<any> {
		return fetch(url, { method: 'put', body })
	}

	delete(url: string, body?: any): Promise<any> {
		return fetch(url, { method: 'delete', body })
	}
}